<template>
  <el-dialog
    :model-value="visible"
    :title="mode === 'create' ? '新建工单' : '编辑工单'"
    width="800px"
    :close-on-click-modal="false"
    @update:model-value="$emit('update:visible', $event)"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      @submit.prevent="handleSubmit"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="工单标题" prop="title">
            <el-input
              v-model="form.title"
              placeholder="请输入工单标题"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="优先级" prop="priority">
            <el-select v-model="form.priority" placeholder="请选择优先级" style="width: 100%">
              <el-option label="高" value="HIGH" />
              <el-option label="中" value="MEDIUM" />
              <el-option label="低" value="LOW" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="分类" prop="category">
            <el-select v-model="form.category" placeholder="请选择分类" style="width: 100%">
              <el-option label="技术问题" value="technical" />
              <el-option label="功能需求" value="feature" />
              <el-option label="Bug修复" value="bug" />
              <el-option label="其他" value="other" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="子分类" prop="subcategory">
            <el-input
              v-model="form.subcategory"
              placeholder="请输入子分类"
              :disabled="!form.category"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="严重程度" prop="severity">
            <el-select v-model="form.severity" placeholder="请选择严重程度" style="width: 100%">
              <el-option label="严重" value="critical" />
              <el-option label="高" value="high" />
              <el-option label="中" value="medium" />
              <el-option label="低" value="low" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="环境" prop="environment">
            <el-select v-model="form.environment" placeholder="请选择环境" style="width: 100%">
              <el-option label="生产环境" value="production" />
              <el-option label="测试环境" value="testing" />
              <el-option label="开发环境" value="development" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="版本" prop="version">
            <el-input
              v-model="form.version"
              placeholder="请输入版本号"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="预计完成时间" prop="dueDate">
            <el-date-picker
              v-model="form.dueDate"
              type="datetime"
              placeholder="选择预计完成时间"
              style="width: 100%"
              format="YYYY-MM-DD HH:mm"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="问题描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="6"
          placeholder="请详细描述问题或需求"
          maxlength="1000"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="重现步骤" prop="steps">
        <el-input
          v-model="form.steps"
          type="textarea"
          :rows="4"
          placeholder="请描述问题的重现步骤（可选）"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="预期结果" prop="expectedResult">
        <el-input
          v-model="form.expectedResult"
          type="textarea"
          :rows="3"
          placeholder="请描述预期的结果（可选）"
          maxlength="300"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="标签" prop="tags">
        <el-select
          v-model="form.tags"
          multiple
          filterable
          allow-create
          placeholder="请选择或输入标签"
          style="width: 100%"
        >
          <el-option
            v-for="tag in availableTags"
            :key="tag"
            :label="tag"
            :value="tag"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="附件" prop="attachments">
        <el-upload
          ref="uploadRef"
          :file-list="fileList"
          :auto-upload="false"
          :limit="5"
          :on-exceed="handleExceed"
          :before-upload="beforeUpload"
          :on-change="handleFileChange"
          :on-remove="handleFileRemove"
          drag
          multiple
        >
          <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              支持 jpg/png/gif/pdf/doc/docx 文件，且不超过 10MB
            </div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">
          {{ submitting ? '保存中...' : '保存' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, watch, computed } from 'vue'
import { useTicketsStore } from '../store/tickets'
import { ElMessage } from 'element-plus'

export default {
  name: 'TicketFormDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    ticket: {
      type: Object,
      default: null
    },
    mode: {
      type: String,
      default: 'create',
      validator: (value) => ['create', 'edit'].includes(value)
    }
  },
  emits: ['update:visible', 'success'],
  setup(props, { emit }) {
    const ticketsStore = useTicketsStore()
    const formRef = ref()
    const uploadRef = ref()
    const submitting = ref(false)
    const fileList = ref([])

    // 表单数据
    const form = reactive({
      title: '',
      description: '',
      priority: 'MEDIUM',
      category: 'other',
      subcategory: '',
      severity: 'medium',
      environment: 'production',
      version: '1.0.0',
      dueDate: '',
      steps: '',
      expectedResult: '',
      tags: [],
      attachments: []
    })

    // 可用标签
    const availableTags = computed(() => [
      '紧急', '重要', '新功能', 'Bug', '优化', '文档', '测试', '部署'
    ])

    // 表单验证规则
    const rules = {
      title: [
        { required: true, message: '请输入工单标题', trigger: 'blur' },
        { min: 5, max: 100, message: '标题长度在 5 到 100 个字符', trigger: 'blur' }
      ],
      description: [
        { required: true, message: '请输入问题描述', trigger: 'blur' },
        { min: 10, max: 1000, message: '描述长度在 10 到 1000 个字符', trigger: 'blur' }
      ],
      priority: [
        { required: true, message: '请选择优先级', trigger: 'change' }
      ],
      category: [
        { required: true, message: '请选择分类', trigger: 'change' }
      ],
      severity: [
        { required: true, message: '请选择严重程度', trigger: 'change' }
      ],
      environment: [
        { required: true, message: '请选择环境', trigger: 'change' }
      ]
    }

    // 监听ticket变化，用于编辑模式
    watch(() => props.ticket, (newTicket) => {
      if (newTicket && props.mode === 'edit') {
        Object.assign(form, {
          title: newTicket.title || '',
          description: newTicket.description || '',
          priority: newTicket.priority || 'MEDIUM',
          category: newTicket.category || 'other',
          subcategory: newTicket.subcategory || '',
          severity: newTicket.severity || 'medium',
          environment: newTicket.environment || 'production',
          version: newTicket.version || '1.0.0',
          dueDate: newTicket.dueDate || '',
          steps: newTicket.steps || '',
          expectedResult: newTicket.expectedResult || '',
          tags: newTicket.tags || [],
          attachments: newTicket.attachments || []
        })
        
        // 设置文件列表
        fileList.value = (newTicket.attachments || []).map((file, index) => ({
          name: file.name || `附件${index + 1}`,
          url: file.url,
          uid: file.id || index
        }))
      }
    }, { immediate: true })

    // 监听对话框显示状态，重置表单
    watch(() => props.visible, (visible) => {
      if (visible && props.mode === 'create') {
        resetForm()
      }
    })

    // 重置表单
    const resetForm = () => {
      Object.assign(form, {
        title: '',
        description: '',
        priority: 'MEDIUM',
        category: 'other',
        subcategory: '',
        severity: 'medium',
        environment: 'production',
        version: '1.0.0',
        dueDate: '',
        steps: '',
        expectedResult: '',
        tags: [],
        attachments: []
      })
      fileList.value = []
      formRef.value?.clearValidate()
    }

    // 文件上传相关方法
    const handleExceed = (files, fileList) => {
      ElMessage.warning(`最多只能上传 5 个文件，当前选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    }

    const beforeUpload = (file) => {
      const isValidType = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'].includes(file.type)
      const isLt10M = file.size / 1024 / 1024 < 10

      if (!isValidType) {
        ElMessage.error('只能上传 jpg/png/gif/pdf/doc/docx 格式的文件!')
        return false
      }
      if (!isLt10M) {
        ElMessage.error('上传文件大小不能超过 10MB!')
        return false
      }
      return true
    }

    const handleFileChange = (file, fileList) => {
      // 文件选择变化时的处理
    }

    const handleFileRemove = (file, fileList) => {
      // 文件移除时的处理
    }

    // 提交表单
    const handleSubmit = async () => {
      if (!formRef.value) return

      try {
        await formRef.value.validate()
        submitting.value = true

        // 准备提交数据
        const submitData = {
          ...form,
          attachments: fileList.value.map(file => ({
            name: file.name,
            url: file.url || file.raw,
            size: file.size,
            type: file.raw?.type || 'unknown'
          }))
        }

        if (props.mode === 'create') {
          await ticketsStore.createTicket(submitData)
          ElMessage.success('工单创建成功！')
        } else {
          await ticketsStore.updateTicket(props.ticket.id, submitData)
          ElMessage.success('工单更新成功！')
        }

        emit('success')
        emit('update:visible', false)
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('提交失败：' + (error.message || '未知错误'))
      } finally {
        submitting.value = false
      }
    }

    // 取消操作
    const handleCancel = () => {
      emit('update:visible', false)
    }

    return {
      formRef,
      uploadRef,
      submitting,
      fileList,
      form,
      availableTags,
      rules,
      handleExceed,
      beforeUpload,
      handleFileChange,
      handleFileRemove,
      handleSubmit,
      handleCancel
    }
  }
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.el-upload__tip {
  color: #606266;
  font-size: 12px;
  margin-top: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .el-dialog {
    width: 95% !important;
    margin: 0 auto;
  }
  
  .el-row {
    flex-direction: column;
  }
  
  .el-col {
    width: 100% !important;
    margin-bottom: 16px;
  }
}
</style>
